package cn.tedu.store.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.tedu.store.bean.Address;
import cn.tedu.store.mapper.AddressMapper;
import cn.tedu.store.service.ex.DataNotFoundException;
@Service("addressService")
public class AddressServiceImpl implements IAddressService {
	@Resource
	private AddressMapper addressMapper;
	
	@Resource(name="districtService")
	private IDistrictService districtService; 
	
	public Integer add(Address address) {
		String recvDistrict=getRecvDistrict(address);
		address.setRecvDistrict(recvDistrict);
		List<Address> addresses=addressMapper.getAddressListByUid(address.getUid());
		Integer isDefault=addresses.size()==0 ? 1 : 0;
		address.setIsDefault(isDefault);
		addressMapper.insert(address);
		Integer id=address.getId();
		return id;
	}
	
	public String getRecvDistrict(Address address) {
		String provinceCode= address.getRecvProvince();
		String provinceName=districtService.getProvinceNameByCode(provinceCode);
		String cityCode=address.getRecvCity();
		String cityName=districtService.getCityNameByCode(cityCode);
		String areaCode=address.getRecvArea();
		String areaName=districtService.getAreaNameByCode(areaCode);
		String recvDistrict=provinceName+cityName+areaName;
		return recvDistrict;
	}

	public List<Address> getAddressListByUid(Integer uid) {
		
		return addressMapper.getAddressListByUid(uid);
	}
	@Transactional
	public Integer delete(Integer id, Integer uid) {
//		Integer affectRows=addressMapper.delete(id, uid);
//		return affectRows;
		Address address=addressMapper.getAddressByIdAndUid(id, uid);
		if(address==null) {
			throw new DataNotFoundException("尝试刷新页面");
		}
		Integer affectRows=addressMapper.delete(id, uid);
		if(address.getIsDefault()==1) {
			List<Address> adds=addressMapper.getAddressListByUid(uid);
			if(adds.size()>0) {
				Integer newDefault=adds.get(0).getId();
				Integer rows= setDefault(uid,newDefault);
				if(rows==0) {
					throw new DataNotFoundException("设置默认失败");
				}
			}
		}else {
			
		}
		return affectRows;
	}

	public Integer update(Address address) {
		String recvDistrict=getRecvDistrict(address);
		address.setRecvDistrict(recvDistrict);
		Integer affectRows=addressMapper.update(address);
		return affectRows;
	}

	public Address getAddressByIdAndUid(Integer id, Integer uid) {
		
		return addressMapper.getAddressByIdAndUid(id, uid);
	}
	@Transactional
	public Integer setDefault(Integer uid, Integer id) {
		Integer rows=addressMapper.cancelAllDefault(uid);
		if(rows==0) {
			throw new DataNotFoundException("取消默认失败");
		}
		Integer affectRows=addressMapper.setDefault(uid, id);
		if(affectRows==0) {
			throw new DataNotFoundException("默认设置失败");
		}
		return affectRows;
		
	}

}
